package com.itheima.controller;


import com.itheima.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "queryByIdFallback")
    public User  findUserById(@PathVariable("id") String username){

//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/"+username;


        String url = "http://user-service/user/"+username;
        if ("haha".equals(username)){
            throw new RuntimeException("hh");
        }

        System.out.println(url);
        User userMap = restTemplate.getForObject(url,User.class);
        return userMap;
    }

    public User queryByIdFallback(String username){
        User user = new User();
        user.setUsername(username);
        user.setName("Controller自带Fallback");
        return user;
    }
}
